package com.servlet;

import com.dao.PMationDao;
import com.dao.impl.PMationImpl;
import com.entry.Zgoods;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.util.PageModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/stock/stockall.do")
public class StockallServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session = req.getSession();
        JsonParser jParser = new JsonParser();
        PMationDao pMationDao = new PMationImpl();
        int pageSize = req.getParameter("pageSize") == null ? 5 : Integer.parseInt(req.getParameter("pageSize").toString());
        int pageNo = req.getParameter("pageNo") == null ? 1 : Integer.parseInt(req.getParameter("pageNo").toString());
        if(req.getParameter("pageNo") == null || req.getParameter("pageSize") == null){
            session.removeAttribute("c1");
        }
        JsonObject jt = null;
        if(session.getAttribute("c1") == null){
            jt = (JsonObject) jParser.parse(req.getParameter("c1"));
        }else{
            jt = (JsonObject) jParser.parse(String.valueOf(session.getAttribute("c1")));
        }
        String zname = jt.get("zname").getAsString();
        try {
            int stacount = "".equals(jt.get("stacount").getAsString()) || jt.get("stacount").getAsString() == null?0:Integer.parseInt(jt.get("stacount").getAsString());
            int endcount = "".equals(jt.get("endcount").getAsString()) || jt.get("endcount").getAsString() == null?0:Integer.parseInt(jt.get("endcount").getAsString());
            JsonObject language1=new JsonObject();
            language1.addProperty("zname", zname);
            language1.addProperty("stacount", String.valueOf(stacount));
            language1.addProperty("endcount", String.valueOf(endcount));
            PageModel<Zgoods> pm = pMationDao.findAl(pageSize,pageNo,zname,stacount,endcount);
            pm.setPageNav(req.getRequestURI()+"?c1=" + language1);
            session.setAttribute("c1",language1);
            session.setAttribute("stall",pm);
            resp.sendRedirect("./stockall.jsp");
        }catch (NumberFormatException e){
            resp.sendRedirect("./stockall.jsp");
        }
    }
}
